/**
 *Copyright (c) 2024 watereyes
 * workflow is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan
 * PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package com.koron.workflow.common.controller;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.swan.bean.MessageBean;

import com.koron.util.Constant;
import com.koron.workflow.common.exception.WorkflowException;
import com.koron.workflow.common.util.BusinessCode;

import java.util.List;

/**
 * 全局异常处理
 *
 * @author bin
 */
@ControllerAdvice
public class GlobalExceptionAction {

    private static final Logger LOG = LoggerFactory.getLogger(GlobalExceptionAction.class);

    @ExceptionHandler(Exception.class)
    @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public MessageBean<?> error(Exception ex, HttpServletRequest request) {
        request.setAttribute(Constant.EXCEPTION, ex);
        LOG.error("服务器内部错误：{}", ex);
        MessageBean<String> message = MessageBean.create(BusinessCode.FAILURE.getCode(), BusinessCode.FAILURE.getDescription(), String.class);
        if (ex instanceof WorkflowException) {
            WorkflowException workflowException = (WorkflowException) ex;
            message.setCode(workflowException.getCode());
            message.setDescription(workflowException.getMessage());
            return message;
        }
        return message;
    }

    /**
     * 处理 @Valid 统一参数校验异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(value = HttpStatus.OK)
    @ResponseBody
    public MessageBean<?> validException(MethodArgumentNotValidException ex) {
        List<ObjectError> errors = ex.getBindingResult().getAllErrors();
        return MessageBean.create(-1, errors.get(0).getDefaultMessage(), String.class);
    }
	
}
